package me.flyray.gate.filter;

import me.flyray.gate.utils.FilterUrlUtils;
import me.flyray.gate.utils.RequestExceptionUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.http.HttpServletRequestWrapper;
import com.netflix.zuul.http.ServletInputStreamWrapper;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import me.flyray.auth.client.jwt.UserAuthUtil;
import me.flyray.auth.common.config.UserAuthConfig;
import me.flyray.auth.common.util.jwt.IJWTInfo;
import me.flyray.common.context.BaseContextHandler;
import me.flyray.common.msg.ResponseCode;
import me.flyray.common.util.EntityUtils;
import me.flyray.common.util.FilterUtil;
import me.flyray.common.util.ValidateSign;
/**
 * @Author: bolei
 * @date: 17:50 2018/11/24
 * @Description: 签名拦截器 数据签名校验 接入每个平台都会分配一个 platformId 和 一个 platformKey
 * 这个appid 就是平台编号 加密了 appkey  就是签名用的盐值
 *
 */

@Component
@Slf4j
public class SignFilter extends ZuulFilter {
	@Autowired
	private UserAuthConfig userAuthConfig;
	@Autowired
	private UserAuthUtil userAuthUtil;
	@Autowired
	private FilterUrlUtils filterUrlUtils;
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 3;
    }

    @Override
    public boolean shouldFilter() {
        //return !filterUrlUtils.filterStartWithUrl(0)&&filterUrlUtils.filterStartWithUrl(1);
    	return filterUrlUtils.filterInterceptUrl(1);
    }

    @Override
    public Object run() {
    	RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();
    	/***
		 * 校验签名
		 * */
		String platformId = request.getHeader("platformId");
		if (platformId == null){
			RequestExceptionUtils.setFailedRequest(ResponseCode.PLATFORM_ID_MISSING.getCode(),ResponseCode.PLATFORM_ID_MISSING.getMessage());
			return null;
		}
		String requstParamsStr=EntityUtils.getBodyData(request);
		Map<String, Object>  requstParamsMap = JSON.parseObject(requstParamsStr);
		String sign = (String) requstParamsMap.get("sign");
		if(null==sign|| "".equals(sign)){
			log.info("网关解析传输参数错误:签名为空");
			RequestExceptionUtils.setFailedRequest(ResponseCode.TOKEN_SIGNISNULL_CODE.getCode(),ResponseCode.TOKEN_SIGNISNULL_CODE.getMessage());
			return null;
		}
		//签名的key,根据平台编号从redis中获取key
		requstParamsMap.remove("sign");
		if(!ValidateSign.checkSign(sign, "46964aeddfe512a4fb0b8789de20035c", requstParamsMap)){
			log.info("网关校验传输参数-签名失败:"+"--之前的签名:--"+sign+"---签名盐值--"+"46964aeddfe512a4fb0b8789de20035c"+"---排序后的参数---"+FilterUtil.createLinkString(requstParamsMap));
			RequestExceptionUtils.setFailedRequest(ResponseCode.TOKEN_CHECKSIGNFAIL_CODE.getCode(),ResponseCode.TOKEN_CHECKSIGNFAIL_CODE.getMessage());
			return null;
		}
		final byte[] reqBodyBytes = requstParamsStr.getBytes();
		ctx.setRequest(new HttpServletRequestWrapper(RequestContext.getCurrentContext().getRequest()) {
			@Override
			public ServletInputStream getInputStream() throws IOException {
				return new ServletInputStreamWrapper(reqBodyBytes);
			}
			@Override
			public int getContentLength() {
				return reqBodyBytes.length;
			}
			@Override
			public long getContentLengthLong() {
				return reqBodyBytes.length;
			}
		});
        return null;
    }
    /**
  	 * 返回session中的用户信息
  	 *
  	 * @param request
  	 * @param ctx
  	 * @return
  	 */
  	private IJWTInfo getJWTUser(HttpServletRequest request, RequestContext ctx) throws Exception {
  		String authToken = request.getHeader(userAuthConfig.getTokenHeader());
  		/*if (StringUtils.isEmpty(authToken)) {
  			authToken = request.getParameter("token");
  		}*/
  		ctx.addZuulRequestHeader(userAuthConfig.getTokenHeader(), authToken);
  		BaseContextHandler.setToken(authToken);
  		return userAuthUtil.getInfoFromToken(authToken);
  	}
}
